package br.uniceub.fsw.academicmobile.dao;

/**
 *
 * @author Gilberto Hiragi
 */
import java.sql.*;

public class BD {

    private Connection cn;

    public BD() {
        this.connect("localhost", "academicmobile", "root", "123");
    }

    public BD(String host, String schema, String user, String password) {
        this.connect(host, schema, user, password);
    }

    public void finalize() {
        try {
            this.getCn().close();
        } catch (Exception ex) {
            System.out.println("BD.finalize()-Ex:" + ex.getMessage());
        }
    }

    private void connect(String host, String schema, String user, String password) {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            this.cn = DriverManager.getConnection("jdbc:mysql://" + host + "/" + schema + "?user=" +
                    user + "&password=" + password);
        } catch (Exception ex) {
            System.out.println("BD()-Ex:" + ex.getMessage());
        }
    }

    public ResultSet getResultSet(String SQL) {
        ResultSet rs = null;
        
        if (this.getCn() == null) {
            return rs;
        }

        try {
            Statement st = getCn().createStatement();
            rs = st.executeQuery(SQL);
        } catch (Exception ex) {
            System.out.println("BD.getResultSet()-Ex:" + ex.getMessage());
        }

        return rs;
    }

    public boolean execSQL(String SQL) {
        boolean ret = false;
        
        if (this.getCn() == null) {
            return ret;
        }

        try {
            Statement st = getCn().createStatement();
            if (st.executeUpdate(SQL) >= 0) {
                ret = true;
            }
            st.close();
        } catch (Exception ex) {
            System.out.println("BD.getResultSet()-Ex:" + ex.getMessage());
        }

        return ret;
    }

    public Connection getCn() {
        return cn;
    }
    
    public static void close(Connection con, ResultSet rs, PreparedStatement pstmt) {
	    try {
	    	con.close();
	    	rs.close();
	    	pstmt.close();
		} catch (SQLException e) {
			e.printStackTrace();
		} 
  	
    }
    
    public static void close(Connection con) {
	    try {
	    	con.close();
		} catch (SQLException e) {
			e.printStackTrace();
		} 
  	
    }
    
    public static void close(ResultSet rs) {
	    try {
	    	rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
		} 
  	
    }
    
    public static void close(PreparedStatement pstmt) {
	    try {
	    	pstmt.close();
		} catch (SQLException e) {
			e.printStackTrace();
		} 
  	
    }

}